<template>
  <div class="case-registration-container">
    <el-page-header :content="title" @back="handleBack" class="page-header" />

    <el-card shadow="hover" class="main-card">
      <!-- 待立案报案列表 -->
      <el-table v-if="showPendingList" :data="pendingList" v-loading="listLoading" border size="small">
        <el-table-column prop="reportNo" label="报案号" min-width="180" />
        <el-table-column prop="policyId" label="保单编号" min-width="140" />
        <el-table-column prop="insuredId" label="投保人ID" min-width="120" />
        <el-table-column prop="reporterName" label="报案人" min-width="120" />
        <el-table-column label="报案状态" min-width="120">
          <template #default="scope">
            <el-tag :type="getTagByStatus(scope.row.reportStatus)">{{ getReportStatus(scope.row.reportStatus)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="handleTime" label="受理时间" min-width="180">
          <template #default="scope">{{ formatDateTime(scope.row.handleTime) }}</template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="scope">
            <el-button type="primary" size="small" @click="startRegistration(scope.row)">立案</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="showPendingList" style="display:flex; justify-content:center; margin-top:12px;">
        <el-pagination background layout="prev, pager, next, jumper, ->, total, sizes" :page-size="pagination.pageSize"
          :current-page="pagination.pageNum" :page-sizes="[5, 10, 20, 50]" :total="pagination.total"
          @size-change="onPageSizeChange" @current-change="onPageChange" />
      </div>

      <!-- 详情模式：显示返回列表按钮 -->
      <div v-if="!showPendingList" style="display:flex; justify-content:flex-end; margin-top:12px;">
        <el-button @click="backToPendingList" type="success">返回</el-button>
      </div>

      <!-- 报案信息展示（仅待立案状态显示） -->
      <el-collapse v-if="isShowCaseInfo" class="info-collapse">
        <el-collapse-item title="报案基本信息" name="report">
          <el-descriptions column="1" border>
            <el-descriptions-item label="报案号">{{ reportInfo.reportNo }}</el-descriptions-item>
            <el-descriptions-item label="保单编号">{{ reportInfo.policyId }}</el-descriptions-item>
            <el-descriptions-item label="投保人ID">{{ reportInfo.insuredId }}</el-descriptions-item>
            <el-descriptions-item label="报案人">{{ reportInfo.reporterName }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ reportInfo.reporterPhone }}</el-descriptions-item>
            <el-descriptions-item label="灾祸类型">{{ getDisasterType(reportInfo.disasterType) }}</el-descriptions-item>
            <el-descriptions-item label="灾祸发生时间">{{
              formatDateTime(reportInfo.disasterOccurTime) }}</el-descriptions-item>
            <el-descriptions-item label="灾祸发生地点">{{ reportInfo.disasterLocation }}</el-descriptions-item>
            <el-descriptions-item label="损失情况描述">{{ reportInfo.lossDescription }}</el-descriptions-item>
            <el-descriptions-item label="农户预估损失(元)">{{ formatCurrency(reportInfo.lossEstimate) }}</el-descriptions-item>
            <el-descriptions-item label="报案受理时间">{{ formatDateTime(reportInfo.handleTime) }}</el-descriptions-item>
            <el-descriptions-item label="报案状态">
              <el-tag :type="getReportStatusTagType()">{{ getReportStatus(reportInfo.reportStatus) }}</el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-collapse-item>

        <!-- 查勘信息展示（待立案状态下必显，支持多条查勘记录选择） -->
        <el-collapse-item title="查勘信息" name="survey">
          <!-- 多条查勘记录选择 -->
          <div v-if="surveyList.length > 1" class="survey-selection">
            <el-alert title="发现多条查勘记录，请选择要用于立案的查勘信息" type="info" :closable="false" style="margin-bottom: 15px;" />
            <el-radio-group v-model="selectedSurvey" @change="selectSurvey">
              <div v-for="(survey, index) in surveyList" :key="survey.surveyId" class="survey-option">
                <el-radio :value="survey" class="survey-radio">
                  <div class="survey-option-content">
                    <span class="survey-title">查勘记录 {{ index + 1 }}</span>
                    <span class="survey-details">
                      查勘员: {{ survey.surveyInWorkNo || '未指定' }} |
                      损失: {{ formatCurrency(survey.surveyMoney) }} |
                      状态: {{ getSurveyStatus(survey.surveyStatus) }}
                    </span>
                  </div>
                </el-radio>
              </div>
            </el-radio-group>
          </div>

          <!-- 查勘详情展示 -->
          <el-descriptions column="1" border v-if="selectedSurvey && selectedSurvey.surveyId">
            <!-- <el-descriptions-item label="查勘表ID（surveyId）">{{ selectedSurvey.surveyId }}</el-descriptions-item> -->
            <el-descriptions-item label="查勘员工号">{{ selectedSurvey.surveyInWorkNo || '未指定' }}</el-descriptions-item>
            <el-descriptions-item label="查勘现场照片">
              <div v-if="surveyPhotos.length" class="photo-list">
                <el-image v-for="(url, idx) in surveyPhotos" :key="url" :src="url"
                  style="width: 100px; height: 100px; margin-right: 8px" :preview-src-list="surveyPhotos"
                  :initial-index="idx" fit="cover" />
              </div>
              <span v-else>无照片</span>
            </el-descriptions-item>
            <el-descriptions-item label="查勘损失类型">{{ getLossType(selectedSurvey.lossType) }}</el-descriptions-item>
            <el-descriptions-item label="受灾面积">{{ selectedSurvey.disasterArea ? selectedSurvey.disasterArea + ' 亩' :
              '未填写'
            }}</el-descriptions-item>
            <el-descriptions-item label="损失数量">{{ selectedSurvey.disasterMount || '未填写' }}</el-descriptions-item>
            <el-descriptions-item label="受灾原因">{{ selectedSurvey.disasterReason || '未填写' }}</el-descriptions-item>
            <el-descriptions-item label="实际查勘地点">{{ selectedSurvey.surveyAddress || '未填写' }}</el-descriptions-item>
            <el-descriptions-item label="查勘评估损失(元)">{{ formatCurrency(selectedSurvey.surveyMoney)
            }}</el-descriptions-item>
            <el-descriptions-item label="查勘开始时间">{{ formatDateTime(selectedSurvey.surverStartTime)
            }}</el-descriptions-item>
            <el-descriptions-item label="查勘结束时间">{{ formatDateTime(selectedSurvey.surverEndTime)
            }}</el-descriptions-item>
            <el-descriptions-item label="查勘状态">
              <el-tag type="success">{{ getSurveyStatus(selectedSurvey.surveyStatus) }}</el-tag>
            </el-descriptions-item>
          </el-descriptions>
          <div v-else class="empty-info">
            暂无查勘信息，<span class="highlight">请先完成查勘后再提交立案</span>
          </div>
        </el-collapse-item>
      </el-collapse>

      <!-- 立案表单（移除reportId和surveyId的验证 & 移除立案时间字段） -->
      <el-form ref="registrationFormRef" :model="registrationForm" label-width="160px" :rules="formRules"
        class="registration-form" :disabled="formDisabled" style="margin-top: 20px" v-if="isShowRegistrationForm">
        <!-- 表中必填字段：report_id（关联报案号，自动填充无需验证） -->
        <el-form-item label="报案号" prop="reportId">
          <el-input v-model="registrationForm.reportId" readonly placeholder="自动填充自报案信息" />
        </el-form-item>


        <!-- 表中必填字段：policy_id（冗余-保单编号） -->
        <el-form-item label="保单编号" prop="policyId">
          <el-input v-model="registrationForm.policyId" readonly placeholder="自动填充自报案信息" />
        </el-form-item>

        <!-- 表中必填字段：insured_id（冗余-投保人ID） -->
        <el-form-item label="投保人ID" prop="insuredId">
          <el-input v-model="registrationForm.insuredId" readonly placeholder="自动填充自报案信息" />
        </el-form-item>

        <!-- 表中必填字段：registrar_id（立案员ID，改为下拉选择） -->
        <el-form-item label="立案员" prop="registrarId">
          <el-select v-model="registrationForm.registrarId" placeholder="请选择立案员"
            :disabled="formDisabled || !registrarOptions.length" clearable filterable style="width: 100%">
            <el-option v-for="item in registrarOptions" :key="item.workNo" :label="`${item.realName}（${item.workNo}）`"
              :value="item.workNo" />
          </el-select>
        </el-form-item>
        <!-- 表中必填字段：farmer_loss_estimate（农户自报损失） -->
        <el-form-item label="农户预估损失(元)" prop="farmerLossEstimate">
          <el-input v-model="registrationForm.farmerLossEstimate" readonly placeholder="填充自报案信息"
            :disabled="formDisabled" />
        </el-form-item>

        <!-- 表中必填字段：surveyor_loss_estimate -->
        <el-form-item label="立案员预估损失(元)" prop="surveyorLossEstimate">
          <el-input v-model="registrationForm.surveyorLossEstimate" placeholder="请根据查勘记录综合评估损失"
            :disabled="formDisabled" />
        </el-form-item>

        <!-- 表中可选字段：loss_diff_reason（损失差异原因） -->
        <el-form-item label="损失差异原因" prop="lossDiffReason" v-if="isLossDiff()">
          <el-input v-model="registrationForm.lossDiffReason" type="textarea" rows="3"
            placeholder="当农户自报与查勘评估差异≥20%时，需说明原因（如：农户高估损失，查勘实际损失较少）" :disabled="formDisabled" />
        </el-form-item>

        <!-- 表中必填字段：loss_type（损失类型） -->
        <el-form-item label="损失类型" prop="lossType" v-if="isShowSelectComponents">
          <el-select v-model="registrationForm.lossType" placeholder="请选择损失类型" :disabled="formDisabled">
            <el-option label="部分损失" value="1" />
            <el-option label="全部损失" value="2" />
            <el-option label="死亡损失" value="3" />
            <el-option label="其他损失" value="4" />
          </el-select>
        </el-form-item>

        <!-- 表中必填字段：loss_scope（损失范围） -->
        <el-form-item label="损失范围" prop="lossScope">
          <el-input v-model="registrationForm.lossScope" type="textarea" rows="3"
            placeholder="请填写具体损失范围（如：5亩玉米倒伏、3头母猪死亡）" :disabled="formDisabled" />
        </el-form-item>

        <!-- 表中必填字段：is_covered（是否属于保险责任） -->
        <el-form-item label="是否属于保险责任" prop="isCovered" v-if="isShowSelectComponents">
          <el-select v-model="registrationForm.isCovered" placeholder="请选择责任认定结果" :disabled="formDisabled">
            <el-option label="属于保险责任" :value="1" />
            <el-option label="不属于保险责任" :value="0" />
          </el-select>
        </el-form-item>

        <!-- 表中必填字段：coverage_basis（责任认定依据） -->
        <el-form-item label="责任认定依据" prop="coverageBasis">
          <el-input v-model="registrationForm.coverageBasis" type="textarea" rows="2"
            placeholder="请填写责任认定依据（如：符合《农业保险条款》第3条第1款）" :disabled="formDisabled" />
        </el-form-item>

        <!-- 表中默认字段：registration_status（立案状态，默认1-已立案） -->
        <el-form-item label="立案状态" prop="registrationStatus">
          <el-input v-model="registrationForm.registrationStatusText" readonly :disabled="true" />
        </el-form-item>

        <!-- 提交按钮：仅待立案+查勘完成（有surveyId）时启用 -->
        <el-form-item class="form-actions">
          <el-button @click="handleReset" :disabled="formDisabled">重置表单</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading"
            :disabled="formDisabled || !registrationForm.surveyId || (selectedSurvey && selectedSurvey.surveyStatus !== 3)">
            提交立案
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, watch, computed, onBeforeUnmount, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElNotification, ElLoading, ElMessageBox } from 'element-plus'

import axios from 'axios'
import hxxp from '@/utils/hxxp'

// 路由实例
const router = useRouter()

// 核心状态变量（基于数据库表设计）
const submitLoading = ref(false)
const formDisabled = ref(true) // 表单默认禁用
const title = computed(() => '新增立案记录')

// 待立案报案列表相关状态
const listLoading = ref(false)
const pendingList = ref([])
const pagination = reactive({ pageNum: 1, pageSize: 5, total: 0 })
const pendingFilters = reactive({ reportStatus: 3 })
const showPendingList = ref(true)

// 新增：立案员下拉选项（存储后端返回的立案员列表）
const registrarOptions = ref([])
// 新增：立案员列表加载状态（用于加载中提示）
const registrarLoading = ref(false)


// 报案信息（映射ai_claim_report表字段）
const reportInfo = reactive({})

// 查勘信息（映射ai_survey_report表字段，核心字段为surveyId）
const surveyInfo = reactive({})
// 多条查勘记录列表
const surveyList = ref([])
// 当前选中的查勘记录
const selectedSurvey = ref(null)

// 立案表单（核心：移除registrationTime字段，由后端生成；reportId和surveyId自动填充）
const registrationForm = reactive({
  registrationId: '', // 后端生成主键
  reportId: '', // 关联报案号（自动填充）
  surveyId: '', // 关联查勘表ID（自动填充）
  policyId: '', // 关联保单编号（自动填充）
  insuredId: '', // 关联投保人ID（自动填充）
  // 移除：registrationTime: '', // 立案时间（后端生成，前端不再维护）
  registrarId: '', // 立案员ID（改为下拉选择，值为workerId）
  farmerLossEstimate: 0.00, // 农户自报损失（自动填充）
  surveyorLossEstimate: '', // 立案员预估损失（用户手动输入）
  lossDiffReason: '', // 损失差异原因（按需填写）
  lossType: null, // 损失类型（下拉选择）
  lossScope: '', // 损失范围（手动填写）
  isCovered: null, // 是否属于保险责任（下拉选择）
  coverageBasis: '', // 责任认定依据（手动填写）
  registrationStatus: 1, // 默认已立案
  registrationStatusText: '已立案（默认）',
  cancelReason: ''
})

// 表单引用
const registrationFormRef = ref(null)

// 计算属性：控制显示逻辑（确保自动填充字段存在才显示表单）
const isShowCaseInfo = computed(() => {
  return reportInfo.reportNo &&
    typeof reportInfo.reportStatus === 'number' &&
    reportInfo.reportStatus === 3 // 仅待立案状态显示
})

const isShowRegistrationForm = computed(() => {
  // 仅当报案信息完整、查勘表ID存在时显示表单
  return isShowCaseInfo.value &&
    Object.keys(reportInfo).length > 0 &&
    reportInfo.policyId &&
    reportInfo.insuredId &&
    selectedSurvey.value && selectedSurvey.value.surveyId // 查勘表ID非空（自动获取后才显示）
})

const isShowSelectComponents = computed(() => {
  return isShowRegistrationForm.value &&
    !formDisabled.value &&
    registrationForm.lossType !== undefined
})

// 表单验证规则（核心：1.删除reportId和surveyId的验证规则；2.删除registrationTime的验证规则；3.保留registrarId验证）
const formRules = reactive({

  policyId: [
    { required: true, message: '关联保单编号不能为空', trigger: 'blur' }
  ],
  insuredId: [
    { required: true, message: '关联投保人ID不能为空', trigger: 'blur' }
  ],
  // 保留registrarId验证（下拉选择仍需确保必填，值格式由后端保证）
  registrarId: [
    { required: true, message: '请选择立案员', trigger: 'change' }, // 触发方式改为change（下拉选择触发）
    { pattern: /^[A-Za-z0-9]{5,32}$/, message: '立案员ID为5-32位字母或数字', trigger: 'change' }
  ],
  farmerLossEstimate: [
    { required: true, message: '农户自报损失不能为空', trigger: 'blur' },
    { type: 'number', min: 0, message: '损失金额不能为负数', trigger: 'blur' }
  ],
  surveyorLossEstimate: [
    { required: true, message: '请输入立案员预估损失', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入立案员预估损失'))
        } else {
          const numValue = Number(value)
          if (isNaN(numValue)) {
            callback(new Error('请输入有效的数字'))
          } else if (numValue < 0) {
            callback(new Error('损失金额不能为负数'))
          } else {
            callback()
          }
        }
      },
      trigger: 'blur'
    }
  ],
  lossType: [
    { required: true, message: '请选择损失类型', trigger: 'change' }
  ],
  lossScope: [
    { required: true, message: '请填写损失范围', trigger: 'blur' },
    { min: 5, message: '损失范围描述不少于5个字符（如：1亩小麦受灾）', trigger: 'blur' }
  ],
  isCovered: [
    { required: true, message: '请选择是否属于保险责任', trigger: 'change' }
  ],
  coverageBasis: [
    { required: true, message: '请填写责任认定依据', trigger: 'blur' },
    { min: 5, message: '认定依据不少于5个字符（如：符合条款第3条）', trigger: 'blur' }
  ]
})

// ---------------------- 字典映射（严格匹配表注释）----------------------
const disasterTypeMap = { 1: '暴雨', 2: '洪水', 3: '病虫害', 4: '疫病', 5: '其他' }
const reportStatusMap = { 1: '待调度', 2: '待查勘', 3: '待立案', 4: '已立案', 5: '已驳回' }
const surveyStatusMap = { 1: '待查勘', 2: '查勘中', 3: '已查勘' }
const lossTypeMap = { 1: '作物', 2: '牲畜', 3: '农机', 4: '其他' }

// ---------------------- 工具函数 ----------------------
// 格式化金额（保留2位小数）
const formatCurrency = (value) => {
  if (!value && value !== 0) return '0.00'
  return Number(value).toFixed(2)
}

// 格式化日期时间
const formatDateTime = (value) => {
  if (!value) return '未填写'
  return new Date(value).toLocaleString('zh-CN', {
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit', second: '2-digit'
  })
}

// 获取字典文本（灾祸类型、报案状态等）
const getDisasterType = (value) => disasterTypeMap[value] || '未知'
const getReportStatus = (value) => reportStatusMap[value] || '未知'
const getSurveyStatus = (value) => surveyStatusMap[value] || '未知'
const getLossType = (value) => lossTypeMap[value] || '未知'

// 列表用：根据报案状态返回标签类型
const getTagByStatus = (status) => {
  switch (status) {
    case 3: return 'warning'
    case 4: return 'success'
    case 5: return 'danger'
    default: return 'info'
  }
}

// 解析查勘照片（逗号分隔，可能带有前缀@）
const surveyPhotos = computed(() => {
  const raw = selectedSurvey.value?.surveyPhoto || surveyInfo.surveyPhoto
  if (!raw || typeof raw !== 'string') return []
  return raw
    .split(',')
    .map(s => s && typeof s === 'string' ? s.trim() : '')
    .map(s => s.startsWith('@') ? s.slice(1) : s)
    .filter(Boolean)
})

// 获取待立案报案列表
const fetchPendingReports = async () => {
  try {
    listLoading.value = true
    const { pageNum, pageSize } = pagination
    const { policyId } = pendingFilters
    const res = await hxxp.get('/aiClaimReport/all', {
      params: { pageNum, pageSize, policyId: policyId || undefined, reportStatus: 3 }
    })
    console.log(res);

    if (res && res.code === 100200) {
      const pageData = res.data || { list: [], total: 0 }
      pendingList.value = Array.isArray(pageData.list) ? pageData.list : []
      pagination.total = Number(pageData.total || pendingList.value.length)
    } else {
      pendingList.value = []
      pagination.total = 0
      ElMessage.error(res.data?.msg || '获取待立案列表失败')
    }
  } catch (e) {
    console.error('获取待立案列表失败:', e)
    pendingList.value = []
    pagination.total = 0
    ElMessage.error('网络异常，获取待立案列表失败')
  } finally {
    listLoading.value = false
  }
}

const onPageChange = (page) => {
  pagination.pageNum = page
  fetchPendingReports()
}

const onPageSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNum = 1
  fetchPendingReports()
}



// 获取报案状态标签类型（视觉区分）
const getReportStatusTagType = () => {
  switch (reportInfo.reportStatus) {
    case 3:
      return 'warning';
    case 4:
      return 'success';
    case 5:
      return 'danger'
    default:
      return 'info'
  }
}

// 判断损失差异是否需填写原因（差异≥20%）
const isLossDiff = () => {
  const farmerLoss = Number(registrationForm.farmerLossEstimate)
  const surveyorLoss = Number(registrationForm.surveyorLossEstimate)
  if (farmerLoss === 0) return false
  const diffRate = Math.abs((surveyorLoss - farmerLoss) / farmerLoss)
  return diffRate >= 0.2
}

// ---------------------- 新增：获取立案员列表（仿调度员方法，调用aiStaffUser/worker接口）----------------------
const getRegistrarList = async () => {
  // 加载状态置为true（如需显示加载中可配合el-select的loading属性）
  registrarLoading.value = true
  try {
    // 调用后端aiStaffUser/worker接口，传参positionCode=PTN001（立案员岗位编码）
    const response = await hxxp.get('aiStaffUser/worker', {
      params: {
        positionCode: 'PTN006' // 固定立案员岗位编码，与后端约定
      }
    })

    if (response.code === 100200) {
      // 后端返回格式预期：[{workerId: 'YG2024001', workerName: '张三'}, ...]
      // registrarOptions.value = response.data || []
      registrarOptions.value = (response.data || []).map(staff => ({
        workNo: staff.workNo,    // 提取工号
        realName: staff.realName // 提取姓名
      }))
      // 若无立案员数据，提示用户
      if (registrarOptions.value.length === 0) {
        ElMessage.warning('当前无可用立案员，请联系管理员配置')
      }
    } else {
      // 响应成功但状态码异常
      ElMessage.error(`获取立案员列表失败：${response.msg || '未知错误'}`)
      registrarOptions.value = []
    }
  } catch (error) {
    // 接口调用失败（网络错误、超时等）
    console.error('获取立案员列表接口调用失败:', error)
    ElMessage.error('获取立案员列表失败，请检查网络或联系管理员')
    registrarOptions.value = []
  } finally {
    // 无论成功失败，加载状态置为false
    registrarLoading.value = false
  }
}

// 选择查勘记录
const selectSurvey = (survey) => {
  selectedSurvey.value = survey
  Object.assign(surveyInfo, survey)
  // 重新填充表单数据
  fillRegistrationForm()
}

// ---------------------- 核心业务逻辑 ----------------------
// 1. 从列表开始立案：加载报案+查勘并开启表单
const startRegistration = async (row) => {
  try {
    formDisabled.value = true
    // 加载报案详情
    const reportRes = await hxxp.get(`/aiClaimReport/${row.reportNo}`)
    if (!(reportRes.code === 100200 && reportRes.data)) {
      throw new Error(reportRes.msg || '未查询到报案信息')
    }
    Object.assign(reportInfo, reportRes.data)

    // 加载查勘详情（按报案号，可能返回多条记录）
    const surveyRes = await hxxp.get(`/aiSurveyReport/${row.reportNo}`)
    if (surveyRes.code === 100200 && surveyRes.data) {
      // 处理多条查勘记录
      const surveyData = surveyRes.data
      if (Array.isArray(surveyData)) {
        surveyList.value = surveyData
        if (surveyData.length === 0) {
          throw new Error('未查询到查勘信息，请先完成查勘')
        } else if (surveyData.length === 1) {
          // 只有一条记录，直接选中
          selectedSurvey.value = surveyData[0]
          Object.assign(surveyInfo, surveyData[0])
        } else {
          // 多条记录，需要用户选择
          surveyList.value = surveyData
          // 默认选择第一条记录
          selectedSurvey.value = surveyData[0]
          Object.assign(surveyInfo, surveyData[0])
        }
      } else {
        // 单条记录的情况（兼容旧接口）
        surveyList.value = [surveyData]
        selectedSurvey.value = surveyData
        Object.assign(surveyInfo, surveyData)
      }

      if (selectedSurvey.value && selectedSurvey.value.surveyId) {
        fillRegistrationForm()
        formDisabled.value = false
        await getRegistrarList()
        showPendingList.value = false
      } else {
        throw new Error('查勘信息缺少surveyId，无法提交立案')
      }
    } else {
      throw new Error('未查询到查勘信息，请先完成查勘')
    }
  } catch (e) {
    console.error('开始立案失败:', e)
    ElMessage.error(e.message || '开始立案失败')
  }
}

// 2. 预填充表单（自动赋值reportId和surveyId，移除registrationTime的初始化）
const fillRegistrationForm = () => {
  registrationForm.reportId = reportInfo.reportNo || '' // 关联报案号自动填充
  registrationForm.surveyId = selectedSurvey.value?.surveyId || surveyInfo.surveyId || '' // 查勘表ID自动填充
  registrationForm.policyId = reportInfo.policyId || ''
  registrationForm.insuredId = reportInfo.insuredId || ''
  registrationForm.farmerLossEstimate = reportInfo.lossEstimate || 0.00
  // 立案员预估损失不自动填充，由用户自行填写
  registrationForm.surveyorLossEstimate = ''
  registrationForm.lossScope = reportInfo.lossDescription || ''
  // 移除：registrationTime的初始化（后端生成，前端不再设置）
  // 初始化下拉字段
  registrationForm.lossType = null
  registrationForm.isCovered = null
  // 新增：重置立案员选择（避免残留旧值）
  registrationForm.registrarId = ''
}

// 3. 提交立案（无需验证reportId、surveyId和registrationTime）
const handleSubmit = async () => {
  if (!registrationFormRef.value) return

  // 3.1 表单验证（仅验证非自动填充、非后端生成字段）
  try {
    await registrationFormRef.value.validate()
  } catch (error) {
    ElMessage.error('表单验证失败，请检查立案员选择、损失类型等必填项')
    return
  }

  // 3.2 二次确认
  ElMessageBox.confirm(
    '确定提交立案吗',
    '提交确认',
    {
      confirmButtonText: '确定提交',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnClickModal: false,
      dangerouslyUseHTMLString: true
    }
  ).then(async () => {
    submitLoading.value = true
    const loadingInstance = ElLoading.service({
      lock: true, text: '提交中...', background: 'rgba(255,255,255,0.7)'
    })

    try {
      // 3.3 调用新增立案接口（不传递registrationTime，由后端生成）
      const regResponse = await hxxp.post(
        '/aiClaimRegistration',
        registrationForm // 包含自动填充的reportId和surveyId，立案员ID为选择的workerId
      )

      if (regResponse.code !== 100200) {
        throw new Error(regResponse.msg || '新增立案记录失败')
      }

      // 3.4 提交成功反馈
      ElMessage.success(`提交立案成功!`)

      // 重置状态
      handleReset()
      Object.keys(reportInfo).forEach(key => reportInfo[key] = '')
      Object.keys(surveyInfo).forEach(key => surveyInfo[key] = '')
      // 重置查勘相关状态
      surveyList.value = []
      selectedSurvey.value = null
      // 重置立案员选项（避免下次查询残留）
      registrarOptions.value = []

    } catch (error) {
      console.error('提交立案失败:', error)
      ElMessage.error(error.message || '提交失败，请稍后重试')
    } finally {
      submitLoading.value = false
      loadingInstance.close()
    }
  }).catch(() => {
    ElMessage.info('已取消立案提交')
  })
}

// 4. 重置表单（保留自动填充的reportId和surveyId，不处理registrationTime）
const handleReset = () => {
  if (registrationFormRef.value) {
    registrationFormRef.value.resetFields()
  }
  // 保留核心关联字段（避免重置后丢失自动填充值）
  if (reportInfo.reportNo && (selectedSurvey.value?.surveyId || surveyInfo.surveyId)) {
    const { reportId, surveyId, policyId, insuredId, farmerLossEstimate } = registrationForm
    fillRegistrationForm()
    registrationForm.reportId = reportId
    registrationForm.surveyId = surveyId
    registrationForm.policyId = policyId
    registrationForm.insuredId = insuredId
    registrationForm.farmerLossEstimate = farmerLossEstimate
    // 重置立案员选择（保留其他字段时，立案员重新选择）
    registrationForm.registrarId = ''
    // 重置立案员预估损失为空（用户需要重新填写）
    registrationForm.surveyorLossEstimate = ''
  } else {
    Object.keys(registrationForm).forEach(key => {
      registrationForm[key] = key === 'lossType' || key === 'isCovered' ? null : ''
    })
  }
}

// 5. 返回上一页
const handleBack = () => {
  router.back()
}

// 监听surveyId变化（防止意外清空，仅提示无需验证）
watch(() => registrationForm.surveyId, (newVal, oldVal) => {
  // 仅在详情模式下校验，返回列表时不提示
  if (showPendingList.value) return
  const isEmpty = !newVal || (typeof newVal === 'string' && newVal.trim() === '')
  if (isEmpty) {
    ElMessage.warning('关联查勘表ID（surveyId）不能为空，已自动恢复为原值')
    registrationForm.surveyId = oldVal
  }
})

// 监听损失金额变化（动态显示差异原因字段）
watch([
  () => registrationForm.farmerLossEstimate,
  () => registrationForm.surveyorLossEstimate
], () => {
  registrationForm.lossDiffReason = registrationForm.lossDiffReason // 触发表单重渲染
})

// 组件卸载前清理
onBeforeUnmount(() => {
  Object.keys(reportInfo).forEach(key => reportInfo[key] = '')
  Object.keys(surveyInfo).forEach(key => surveyInfo[key] = '')
  Object.keys(registrationForm).forEach(key => {
    registrationForm[key] = key === 'lossType' || key === 'isCovered' ? null : ''
  })
  // 清理查勘相关状态
  surveyList.value = []
  selectedSurvey.value = null
  // 清理立案员选项
  registrarOptions.value = []
})

// 初始加载待立案列表
onMounted(() => {
  fetchPendingReports()
})

// 返回未立案列表
const backToPendingList = () => {
  // 清空详情数据
  Object.keys(reportInfo).forEach(key => reportInfo[key] = '')
  Object.keys(surveyInfo).forEach(key => surveyInfo[key] = '')
  Object.keys(registrationForm).forEach(key => {
    registrationForm[key] = key === 'lossType' || key === 'isCovered' ? null : ''
  })
  // 清空查勘相关状态
  surveyList.value = []
  selectedSurvey.value = null
  registrarOptions.value = []
  formDisabled.value = true
  showPendingList.value = true
  fetchPendingReports()
}
</script>

<style scoped>
.case-registration-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.main-card {
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

.search-form {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f2f2f2;
}

.info-collapse {
  margin-bottom: 20px;
}

.empty-info {
  text-align: center;
  padding: 20px;
  color: #666;
  background-color: #f9fafb;
  border-radius: 4px;
}

.highlight {
  color: #f56c6c;
  font-weight: 700;
}

.registration-form {
  background-color: #fff;
  padding: 15px 0;
}

.form-actions {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 禁用状态样式优化 */
.el-form-item.is-disabled .el-input__inner,
.el-form-item.is-disabled .el-select__inner {
  background-color: #f9fafb;
  color: #999;
  cursor: not-allowed;
  border-color: #eee;
}

/* 查勘记录选择样式 */
.survey-selection {
  margin-bottom: 20px;
}

.survey-option {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fafafa;
  transition: all 0.3s;
}

.survey-option:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.survey-radio {
  width: 100%;
}

.survey-option-content {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.survey-title {
  font-weight: 600;
  color: #303133;
}

.survey-details {
  font-size: 12px;
  color: #606266;
}

/* 小屏幕适配 */
@media (max-width: 768px) {
  .registration-form {
    padding: 10px;
  }

  .el-descriptions-item__label {
    width: 140px !important;
    font-weight: 700;
  }

  .form-actions {
    flex-direction: column;
    align-items: stretch;
  }

  .form-actions .el-button {
    width: 100%;
  }

  .survey-option-content {
    font-size: 14px;
  }

  .survey-details {
    font-size: 11px;
  }
}
</style>